<?php

$myusername = $_POST['myusername'];
$mypassword = $_POST['mypassword'];
$mypasswordrepeat = $_POST['mypasswordrepeat'];
$mygroupname = $_POST['mygroupname'];
if ($mypassword == $mypasswordrepeat) {
    if ($mypassword != "") {
        if ($myusername != "") {
            ob_start();
            // Connect to server and select databse.
            include("databaseconnect.php");
            databaseconnect();

            //Encrypt the password
            $encrypted_mypassword = md5($mypassword);
            // To protect MySQL injection (more detail about MySQL injection)
            $myusername = stripslashes($myusername);
            $encrypted_mypassword = stripslashes($encrypted_mypassword);
            $myusername = mysql_real_escape_string($myusername);
            $encrypted_mypassword = mysql_real_escape_string($encrypted_mypassword);


            $SQLCheckname = sprintf("SELECT username FROM auth WHERE username='$myusername'");
            $SQLChecknameRow = mysql_fetch_assoc(mysql_query($SQLCheckname));
            if ($SQLChecknameRow['username'] != $myusername) {

                //Update userid counter
                $sqlusercounter = "SELECT * FROM idcounter WHERE type='userid'";
                $userrow = mysql_fetch_assoc(mysql_query($sqlusercounter));
                $currentuserid = $userrow['id'];
                $newuserid = $userrow['id'] + 1;
                $sqluserupdate = "UPDATE idcounter SET id='$newuserid' WHERE type='userid'";
                mysql_query($sqluserupdate);

                //Extract GroupID
                $sqlgroup = "SELECT * FROM groups WHERE groupname='$mygroupname'";
                $grouprow = mysql_fetch_assoc(mysql_query($sqlgroup));
                $mygroupid = $grouprow['groupid'];
                //Formulate SQL Query
                $sql = "INSERT INTO auth (userid, username, password, groupid) VALUES ('$currentuserid','$myusername','$encrypted_mypassword','$mygroupid')";
                mysql_query($sql);
                session_start();
                $_SESSION[user] = $myusername;
                header("location:adduser_success.php");
            } else {
                echo "User already exists";
            }
            ob_end_flush();
        } else {
            echo "No username entered";
        }
    } else {
        echo "No password entered";
    }
} else {
    echo "Passwords do not match";
}
?>